import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  message,
  Divider,
  Popconfirm,
  Upload,
  Select,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {ruleP,nameMaxLength,nameMinLength,remarkMaxLength} from '@/utils/rule'
import styles from '../search.less';
const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text, } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();

      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑应用系统':'新增应用系统'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="应用系统名称">
        {form.getFieldDecorator('appName', {
          rules: [
            { required: true,whitespace: true, message: '应用系统名称不能为空'},
            { min: nameMinLength()[0], message: nameMinLength()[1] },
            {max:nameMaxLength()[0], message:nameMaxLength()[1]},           
          ],
            initialValue: text&&text.appName || ''
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="应用系统代码">
        {form.getFieldDecorator('appCode', {
          rules: [{ required: true,whitespace: true, message: '应用系统代码不能为空'},
          {pattern:new RegExp(ruleP(13)[0],'g'), message:ruleP(13)[1]},
          {max:nameMaxLength()[0], message:nameMaxLength()[1]},          
        ],          
          initialValue: text&&text.appCode || ''
        })(<Input placeholder="请输入" disabled= {text? true:false} />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="IP地址">
        {form.getFieldDecorator('ipAddr', {
          rules: [{pattern:new RegExp(ruleP(3)[0],'g'), message:ruleP(3)[1]}],initialValue: text&&text.ipAddr || ''
        })(<Input placeholder="请输入" />)}
      </FormItem>
      {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="负责人">
        {form.getFieldDecorator('person', {
          rules: [{ required: true,message: '负责人不能为空'},],initialValue: text&&text.person
        })(<Select placeholder="请选择" showSearch style={{width:'100%'}}>
            {optionList.map(item=><Option value={item.value}>{item.value}/{item.label}</Option>)}
            </Select>
          )}
      </FormItem> */}
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="备注">
        {form.getFieldDecorator('remark',{rules:[
          {max:remarkMaxLength()[0], message:remarkMaxLength()[1]}],
          initialValue: text&&text.remark || ''})(<TextArea
          style={{ minHeight: 32 }}
          rows={2}
        />)}
      </FormItem>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({ bnsSystem, loading }) => ({
  bnsSystem,
  loading: loading.models.bnsSystem,
}))


@Form.create()
class bnsSystem extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,   
    formValues: {},
    selectedRows: [], 
    text: {},  
  };

  columns = [
    // {
    //   title: '序号',
    //   render: (text, record, index) => (
    //     index+1
    //   ),
    // },
    {
      title: '应用系统名称',
      dataIndex: 'appName',
    },
    {
      title: '应用系统代码',
      dataIndex: 'appCode',
    },
    // {
    //   title: '负责人',
    //   dataIndex: 'respUserCode',
    // },
    {
      title: 'IP地址',
      dataIndex: 'ipAddr', 
    },
    {
      title: '备注',
      dataIndex: 'remark',  
      ellipsis:true, 
      width:'30%',  
    },
    {
      title: '操作',
      width:240,
      render: (text, record) => (
        <Fragment>         
           <a onClick={() => this.handleViewKey(true, text)}>查看密码</a>    
          <Divider type="vertical" />
          <a onClick={() => this.updateKey(text.appId)}>更新密码</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.appId)}>删除</a>
        </Fragment>
      ),
    },
  ];

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.appId;
    });
    this.deleteData(ids); //批量删除
  };


  // 删除方法
  handleDeleteData = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bnsSystem/remove',
      payload: { appId: id },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

     //更新密钥  
  updateKey = (id) => {
    Modal.confirm({
      title: '更新密码',
      content: '您确定要更新密码吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleUpdateKey(id),
    });
  };

 handleUpdateKey(id) {
  const { dispatch } = this.props;
  const values = {
    appId:id,
  };
  dispatch({
    type: 'bnsSystem/updateKey',
    payload: values,
    callback: (res) => {
      if(res.result == "ok") {
        Modal.success({title: res.msg});
        this.pageList();      
      }else {
        Modal.error({title: '操作失败',content: res.msg});
      }
    },
  });
}

// 查看密钥
handleViewKey = (flag,text) => {
  this.setState({
    viewKeyModalVisible: !!flag,
    text,
  });
};

    // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      appName: data && data.appName || '',
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'bnsSystem/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询  
      this.pageList(fieldsValue);
    });
  };

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };


  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const params = {
      appId: text.appId,
      appCode:fields.appCode,
      appName:fields.appName,
      ipAddr:fields.ipAddr,
      // respUserCode:fields.respUserCode,
      remark:fields.remark,
    }
    dispatch({
      type: 'bnsSystem/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
           Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const params = {
      appCode:fields.appCode,
      appName:fields.appName,
      ipAddr:fields.ipAddr,
      // respUserCode:fields.respUserCode,
      remark:fields.remark,
    }
    dispatch({
      type: 'bnsSystem/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };


  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="应用系统名称">
              {getFieldDecorator('appName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() { 
    return this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  render() {
    const {
      bnsSystem: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, viewKeyModalVisible,text, } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };
    const viewKeyMethods = {
      handleViewKey: this.handleViewKey,
    };
    return (
      <PageHeaderWrapper title="应用系统管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.appId}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>      
        {viewKeyModalVisible?(
          <ViewKey {...viewKeyMethods} viewKeyModalVisible={viewKeyModalVisible} text={text} />
        ):null}  
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
class ViewKey extends PureComponent {
  render() {
    const { viewKeyModalVisible, handleViewKey,text } = this.props;
    return (
      <Modal
        destroyOnClose
        width={640}
        title="查看密码"
        visible={viewKeyModalVisible}
        onCancel={() => handleViewKey(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleViewKey()}>返回</Button>
        ]}        
      >
    <Row>
      <Col md={24}>
        <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}}  label="密码">
          {text.appSecret}
        </FormItem>
      </Col>      
    </Row>
      </Modal>
    );
  }
}

export default bnsSystem;
